package com.example.retrofitdemo

import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.Observer

/**
 * 只有一个 source 的 MediatorLiveData
 * 避免短时请求造成结果混乱（第二次的结果先于第一次结果返回或者第二次请求过程中显示了第一次请求的结果）
 */
class SingleSourceMediatorLiveData<T> : MediatorLiveData<T>() {
    private var lastSource: LiveData<*>? = null

    override fun <S : Any?> addSource(source: LiveData<S>, onChanged: Observer<in S>) {
        lastSource?.run { removeSource(this) }
        super.addSource(source, onChanged)
        lastSource = source
    }

    override fun <S : Any?> removeSource(toRemote: LiveData<S>) {
        super.removeSource(toRemote)
        lastSource?.run {
            if (this != toRemote) {
                super.removeSource(this)
            }
        }
        lastSource = null
    }
}